package com.oa.demo.auth.service.impl;


import com.oa.demo.auth.entity.TUser;
import com.oa.demo.auth.manager.UserManager;
import com.oa.demo.auth.mapper.TUserMapper;
import com.oa.demo.common.entity.OaAuthUser;
import com.oa.demo.common.entity.system.AuthUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author 孔德成
 * @date 2020/11/20 15:25
 */
@Service
public class UserDetailServiceIml implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserManager userManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        TUser user = userManager.findByName(username);
        if (user != null) {
            String permissions = userManager.findUserPermissions(user.getId());
            boolean notLocked = false;
            if (StringUtils.equals(TUser.STATUS_VALID, user.getStatus())){
                notLocked = true;
            }
            AuthUser authUser = new AuthUser(user.getUsername(), user.getPassword(), true, true, true, notLocked,
                    AuthorityUtils.commaSeparatedStringToAuthorityList(permissions));
            BeanUtils.copyProperties(user,authUser);
            return authUser;
        } else {
            throw new UsernameNotFoundException("");
        }
    }
}
